package com.tiger.service;

import com.tiger.exception.ServiceException;
import com.tiger.pojo.user.User;
import com.tiger.utils.HttpUtils;
import com.tiger.utils.Regex;
import org.apache.http.HttpResponse;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


@Service
public class RegisterServiceImpl implements RegisterService {
	@Autowired
	private UserFingerService registerDao;
	@Override
	public int saveRegister(User user) {
		// TODO Auto-generated method stub
		if(user==null)
		{throw new IllegalArgumentException("未添加信息");}
		String salt=UUID.randomUUID().toString();
		/*spring 的api
		 * String hashedPassword =
		 * DigestUtils.md5DigestAsHex((salt+entity.getPassword()).getBytes());
		 */
		SimpleHash sh=new SimpleHash("MD5", user.getPassword(), salt, 1);
		String hashedPassword = sh.toHex();
		user.setSalt(salt);//登陆时还要使用盐对登陆密码进行加密
		user.setPassword(hashedPassword);
		
		 Integer rows= registerDao.saveRegister(user);
		
		
		if(rows==0) {
			throw new ServiceException("网络有问题");
		}
		
		return rows;
	}
	@Override
	public String verificationCode(String tel) {
		// TODO Auto-generated method stub
		
		//获取随机四位整数
		String code = String.valueOf((int)((Math.random()*9+1)*1000));
		//下面是验证码获取方法
		 String host = "http://yzx.market.alicloudapi.com";
		    String path = "/yzx/sendSms";
		    String method = "POST";
		    String appcode = "52eed18247b14f4aa690e4f6b09e1491";
		    Map<String, String> headers = new HashMap<String, String>();
		    //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
		    headers.put("Authorization", "APPCODE " + appcode);
		    Map<String, String> querys = new HashMap<String, String>();
		    querys.put("mobile", tel);
		    querys.put("param", "code:"+code);
		    querys.put("tpl_id", "TP1710262");
		    Map<String, String> bodys = new HashMap<String, String>();


		    try {
		    	/**
		    	* 重要提示如下:
		    	* HttpUtils请从
		    	* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
		    	* 下载
		    	*
		    	* 相应的依赖请参照
		    	* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
		    	*/
		    	HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
		    	System.out.println(response.toString());
		    	//获取response的body
		    	//System.out.println(EntityUtils.toString(response.getEntity()));
		    } catch (Exception e) {
		    	e.printStackTrace();
		    }
		return code;
	}
	@Override
	public String findByTel(String tel) {
		// TODO Auto-generated method stub
		//校验号码是否格式正确
		Regex.telRegex(tel);
		String result = registerDao.findByTel(tel);
		
		if(result!=null) {
			throw new IllegalArgumentException("该电话号码已经注册过");
		}
		return result;
	}

}
